<template>
	<view class="">

		<view class="jack-file-title" v-if="showTitle">
			<view class="jack-file-title-l">
				{{title}}
			</view>
			<!-- <image :src="currentImage"></image> -->
			<view class="jack-file-title-r">
				{{`${selectedList.length}/${limit}`}}
			</view>
		</view>
		<!-- <uni-file-picker limit="9" title="最多选择9张图片" ref="filepicker" @select="select"></uni-file-picker> -->
		<view class="image_list">
			<view v-for="(item,index) in selectedList" :key="index" class="image_list_imgs">
				<image src="../../static/close.svg" @click="deleteImg(index)" class="image_list_imgs_delete"
					v-if="!readonly&&delIcon"></image>
				<image :src="item" mode="aspectFill" @click="prviewImg(item)" class="image_list_imgs_item"
					show-menu-by-longpress fade-show></image>
			</view>
			<view class="image_list_template" @click="chooseFile" v-if="(selectedList.length<limit)&&!readonly">
				<image src="../../static/add.svg"></image>
			</view>
		</view>
		<uni-popup :is-mask-click="false" mask-background-color="rgb(0,0,0,0.8)" ref="popup" type="center"
			border-radius="10px 10px 0 0">
			<view class="popup">
				<view style="position: fixed;top:20px; color: red;">123</view>
				<view class="content-box" :style="{'overflow':(notMoveCanvas?'hidden':'auto')}">
					<view class="canvas" :style="{height: canvasHeight +'px'}">
						<canvas canvas-id="newCanvas"
							:style="{'width':itemCanvasInfo.width+'px','height':itemCanvasInfo.height+'px'}"></canvas>
						<canvas canvas-id="itemCanvas" class="canvasDom" ref="itemCanvas"
							:style="{'width':itemCanvasInfo.width+'px','height':itemCanvasInfo.height+'px'}"></canvas>
						<canvas :style="{'width':'100%','height':canvasHeight+'px'}" canvas-id="imgCanvas"
							class="canvasDom"></canvas>
						<canvas :style="{'width':'100%','height':canvasHeight+'px'}" canvas-id="drawCanvas"
							@touchmove="touchmove" @touchstart="touchstart" @touchend="touchend"
							class="canvasDom"></canvas>
						<canvas :style="{'width':'100%','height':canvasHeight+'px'}" canvas-id="timeCanvas"
							@touchmove="touchmove" @touchstart="touchstart" @touchend="touchend"
							class="canvasDom"></canvas>
						<canvas :style="{'width':'100%','height':canvasHeight+'px'}" canvas-id="addressCanvas"
							@touchmove="touchmove" @touchstart="touchstart" @touchend="touchend"
							class="canvasDom"></canvas>
						<canvas :style="{'width':'100%','height':canvasHeight+'px'}" canvas-id="clipCanvas"
							@touchmove="touchmove" @touchstart="touchstart" @touchend="touchend"
							class="canvasDom"></canvas>
					</view>
				</view>
			</view>

			<view class="tools">
				<view class="tools_item" @click="!btnCanotUse?addMark('time'):()=>{}"
					:class="[!btnCanotUse?'':'disabled']">
					<image src="../../static/time.svg"></image>
					<text v-if="!dateTimeInfo.hash">当前时间</text>
					<text v-if="dateTimeInfo.hash">清除时间</text>
				</view>
				<view class="tools_item" @click="!btnCanotUse?addMark('address'):()=>{}"
					:class="[!btnCanotUse?'':'disabled']">
					<image src="../../static/coordinates.svg"></image>
					<text v-if="!addressInfo.hash">地点</text>
					<text v-if="addressInfo.hash">清除地点</text>
				</view>
				<view class="tools_item" @click="!btnCanotUse?addMark('rotate'):()=>{}"
					:class="[!btnCanotUse?'':'disabled']">
					<image src="../../static/refresh.svg"></image>
					<text>旋转</text>
				</view>
				<view class="tools_item" @click="!canDraw?addMark('clip'):()=>{}" :class="[canDraw?'disabled':'']">
					<image src="../../static/tailor.svg"></image>
					<text v-if="!isClip">裁剪</text>
					<text v-if="isClip">关闭裁剪</text>
				</view>
				<view class="tools_item">
					<view class="tools_item_strokesetting" v-if="canDraw">
						<view class="tools_item_strokesetting_item">
							<view class="tools_item_strokesetting_item_selector" style="height: 40rpx;">
								<view v-for="item in colorList" @click="strokeInfo.color=item"
									:style="{'background':(item!='clear'?item:'radial-gradient(#555555 1px, white 1px) repeat'),'background-size':'4px 4px'}"
									:class="['colorbox',(item==strokeInfo.color)?'tools_item_strokesetting_item_selector_active':'']">
								</view>
							</view>
							<view style="height: 40rpx;">
								<!-- <view v-for="item in weightList" @click="strokeInfo.weight=item"
									:class="[(item==strokeInfo.weight)?'tools_item_strokesetting_item_selector_active':'']"
									:style="{'background': 'black','height':'40rpx','width':'40rpx',
									'border-radius':'50%','border-width':(14-item)+'rpx','box-sizing':'border-box',
									'border-color':'transparent','background-clip':' content-box',}">
								</view> -->
								<slider :value="strokeInfo.weight" :min="2" :max="15" block-size="18"
									@change="sliderChange" show-value />
							</view>
						</view>
					</view>
					<image src="../../static/brush.svg" @click="!isClip?addMark('draw'):()=>{}"
						:class="[isClip?'disabledClip':'']"></image>
					<text @click="!isClip?addMark('draw'):()=>{}"
						:class="[isClip?'disabledClip':'']">{{canDraw?'停止涂鸦':'涂鸦'}}</text>
				</view>

				<view class="tools_item" @click="!btnCanotUse?addMark('save'):()=>{}"
					:class="[!btnCanotUse?'':'disabled']">
					<image src="../../static/right.svg"></image>
					<text>保存</text>
				</view>
				<view class="tools_item" :class="[!btnCanotUse?'':'disabled']" @click="!btnCanotUse?exit():()=>{}">
					<image src="../../static/close.svg"></image>
					<text>退出</text>
				</view>
				<!-- <button>当前时间</button>
				<button>当前地点</button>
				<button>涂鸦</button> -->
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {
		amapKey,
		securityJsCode,
	} from "@/uni_modules/jack-filepicker/common/config.js"
	// #ifdef H5
	import AMapLoader from '@amap/amap-jsapi-loader';
	// #endif
	let sto = null
	let sto1 = null
	import {
		getNowDateTime,
		rpx2px,
		rpxTopx,
		base64toBlob,
		blobToUrl,
		canvasHasContent,
		urlImgRotate,
		base64ToWxfile,

	} from "../../utils/index.js"
	// #ifdef MP-WEIXIN
	var newCanvas = null
	// #endif
	var imgCanvas = null
	var timeCanvas = null
	var drawCanvas = null
	var clipCanvas = null
	var itemCanvas = null
	var addressCanvas = null
	export default {
		name: 'JackFileupload',
		props: {
			limit: {
				type: Number,
				default: 1
			},
			readonly: {
				type: Boolean,
				default: false
			},
			disablePreview: {
				type: Boolean,
				default: false
			},
			delIcon: {
				type: Boolean,
				default: true
			},
			title: {
				type: String,
				default: '请选择图片'
			},

			sourceType: {
				type: Array,
				dafaule: () => {
					return ['album', 'camera']
				}
			},
			fileExtname: {
				type: Array,
				default: () => ['.png', '.jpg', '.jpeg', '.webp']
			},
			value: {
				type: Array,
				default: () => []
			},
			showTitle: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				moveAddress: false,
				// 裁剪截取的每一层的宽高
				itemCanvasInfo: {
					width: 0,
					height: 0
				},
				fourPointRange: [],
				// 旋转的角度
				rotateDeg: 0,
				selectedList: [],
				moveTime: false,
				colorList: [
					'red',
					'orange',
					'black',
					'white',
					'green',
					'clear'
				],
				weightList: [
					2,
					5,
					8,
					11,
					13
				],
				strokeInfo: {
					weight: 2,
					color: 'red'
				},
				canDraw: false,
				canvasHeight: 0,
				imageValue: [],
				currentImage: {},
				currentImgInfo: {
					width: 0,
					height: 0
				},
				screenInfo: {
					width: 0,
					height: 0
				},
				drawImageInfo: {
					width: 0,
					height: 0
				},
				dateTimeInfo: {
					left: 0,
					top: 0,
					hash: false,
					nowTime: ''
				},
				addressInfo: {
					left: 0,
					top: 0,
					hash: false,
					currentAdd: '',
					addressWidth: 120
				},
				marginL: 0,
				touches: [],
				// 触摸偏移量
				textOffset: {
					left: 0,
					top: 0
				},
				addressOffset: {
					left: 0,
					top: 0
				},
				scaleCanvas: 1,
				// oOffset: 0, //两指触摸后的初始距离
				isClip: false, //是否裁剪
				radius: 10, //顶点半径
				currentTouchPoint: {}, //当前点的位置
				isMovePoint: false, //是否在移动顶点
				AMap: null,
			}
		},
		methods: {
			sliderChange(e) {
				this.strokeInfo.weight = e.detail.value
			},
			exit() {
				uni.showModal({
					content: '是否退出编辑？',
					confirmText: '继续编辑',
					title: '操作将删除此图片',
					cancelText: '退出编辑',
					success: (e) => {
						if (e.cancel) {
							this.clearCanvas()
							this.clearCanvasContent()
						}
					}
				})
			},
			/**
			 * @param {Object} index
			 * 删除图片
			 */
			deleteImg(index) {
				let url = this.selectedList.splice(index, 1)[0]
				this.$emit('delete', {
					index: index,
					url: url
				})
				this.$emit('input', this.selectedList)
			},
			/**
			 * @param {Object} img
			 * 预览图片
			 */
			prviewImg(index) {
				if (this.disablePreview) {
					uni.showToast({
						icon: 'none',
						title: '禁止查看'
					})
				} else {
					uni.previewImage({
						urls: this.selectedList,
						showmenuL: true,
						current: index,
						indicator: 'number',
						loop: true,
					})
				}
			},
			/**
			 * c是否在一个矩形区域t内
			 * @param {x,y} c
			 * @param {x1,y1,x2,y2} t
			 */
			isMoveIn(c, t) {
				if (c.x > t.x1 && c.x < t.x2 && c.y > t.y1 && c.y < t.y2) {
					return true
				}
				return false
			},
			// 手指开始接触
			touchstart(e) {
				this.currentTouchPoint = e.touches[0]
				this.textOffset.left = e.touches[0].x - this.dateTimeInfo.left
				this.textOffset.top = e.touches[0].y - this.dateTimeInfo.top
				this.addressOffset.left = e.touches[0].x - this.addressInfo.left
				this.addressOffset.top = e.touches[0].y - this.addressInfo.top
				if (this.canDraw) {
					drawCanvas.moveTo(e.touches[0].x, e.touches[0].y)
				}
			},
			// 接触结束
			touchend(e) {
				this.textOffset.left = 0
				this.textOffset.top = 0
				this.addressOffset.left = 0
				this.addressOffset.top = 0
				this.oOffset = 0
			},

			// 接触后移动
			touchmove(e) {
				this.touches = e.touches
				// 判断是否要移动元素
				if (this.touches.length == 1) {

					// 移动时间
					// 判断在手指是否在时间元素内
					if (!this.canDraw && this.dateTimeInfo.hash && this.isMoveIn({
							x: this.touches[0].x,
							y: this.touches[0].y
						}, {
							x1: this.dateTimeInfo.left,
							y1: this.dateTimeInfo.top - 15,
							x2: this.dateTimeInfo.left + 120,
							y2: this.dateTimeInfo.top + 5,
						})) {
						this.moveTime = true
						if (sto) {
							clearTimeout(sto)
						}
						sto = setTimeout(() => {
							this.moveTime = false
							clearTimeout(sto)
							sto = null
						}, 200)

						let l = this.touches[0].x - this.textOffset.left
						// 碰到左边缘
						if (l < 0) {
							this.dateTimeInfo.left = 0
						}
						// 碰到右边缘
						else if (l + 120 > this.screenInfo.width) {
							this.dateTimeInfo.left = this.screenInfo.width - 120
						} else {
							this.dateTimeInfo.left = l
						}
						let t = this.touches[0].y - this.textOffset.top
						// 碰到上边缘
						if (t < 10) {
							this.dateTimeInfo.top = 10
						} else if (t > this.canvasHeight - 10) {
							// 碰到下边缘
							this.dateTimeInfo.top = this.canvasHeight - 10
						} else {
							this.dateTimeInfo.top = t
						}
						this.reDrawTime()
					}
					// 移动地点位置
					if (!this.canDraw && this.addressInfo.hash && this.isMoveIn({
							x: this.touches[0].x,
							y: this.touches[0].y
						}, {
							x1: this.addressInfo.left,
							y1: this.addressInfo.top - 15,
							x2: this.addressInfo.left + this.addressInfo.addressWidth,
							y2: this.addressInfo.top + 5,
						})) {
						this.moveAddress = true
						if (sto1) {
							clearTimeout(sto1)
						}
						sto1 = setTimeout(() => {
							this.moveAddress = false
							clearTimeout(sto1)
							sto1 = null
						}, 200)

						let l = this.touches[0].x - this.addressOffset.left
						// 碰到左边缘
						if (l < 0) {
							this.addressInfo.left = 0
						}
						// 碰到右边缘
						else if (l + this.addressInfo.addressWidth > this.screenInfo.width) {
							this.addressInfo.left = this.screenInfo.width - this.addressInfo.addressWidth
						} else {
							this.addressInfo.left = l
						}
						let t = this.touches[0].y - this.addressOffset.top
						// 碰到上边缘
						if (t < 10) {
							this.addressInfo.top = 10
						} else if (t > this.canvasHeight - 10) {
							// 碰到下边缘
							this.addressInfo.top = this.canvasHeight - 10
						} else {
							this.addressInfo.top = t
						}
						this.reDrawAddress()
					}
					// 涂鸦
					if (this.canDraw) {
						if (this.strokeInfo.color != 'clear') {
							drawCanvas.setStrokeStyle(this.strokeInfo.color)
							drawCanvas.setLineCap('round')
							drawCanvas.setLineWidth(this.strokeInfo.weight)
							drawCanvas.lineTo(this.touches[0].x, this.touches[0].y)
							drawCanvas.stroke()
							drawCanvas.draw(true)
							drawCanvas.moveTo(this.touches[0].x, this.touches[0].y)
						} else {
							//擦除
							drawCanvas.clearRect(this.touches[0].x - this.strokeInfo.weight / 2, this.touches[0].y - this
								.strokeInfo.weight / 2, this.strokeInfo.weight, this.strokeInfo.weight)
							drawCanvas.draw(true)
						}
					}
					// 移动裁剪顶点
					if (this.isClip) {
						this.fourPointRange.forEach((i, index) => {
							if (this.isMoveIn({
									x: this.touches[0].x,
									y: this.touches[0].y
								}, i)) {
								// 是否在移动点
								this.isMovePoint = true
								this.moveTime = true
								if (sto) {
									clearTimeout(sto)
								}
								sto = setTimeout(() => {
									this.moveTime = false
									this.isMovePoint = false
									clearTimeout(sto)
									sto = null
								}, 200)
								// 禁止移出外边界
								if (this.touches[0].x < this.radius) {
									this.touches[0].x = this.radius
								}
								if (this.touches[0].x > this.screenInfo.width - this.radius) {
									this.touches[0].x = this.screenInfo.width - this.radius
								}
								if (this.touches[0].y < this.radius) {
									this.touches[0].y = this.radius
								}
								if (this.touches[0].y > this.canvasHeight - this.radius) {
									this.touches[0].y = this.canvasHeight - this.radius
								}
								let x = this.touches[0].x
								let y = this.touches[0].y
								// 重新计算点的位置
								this.reComPointPos(x, y, index)
								// 重绘顶点
								this.drawFourPoint()
							}
						})
						// 不在移动点且在 框选范围内
						if (!this.isMovePoint && this.isMoveIn({
								x: this.touches[0].x,
								y: this.touches[0].y
							}, {
								x1: this.fourPointRange[0].x1,
								y1: this.fourPointRange[0].y1,
								x2: this.fourPointRange[3].x2,
								y2: this.fourPointRange[3].y2,
							})) {
							// 在框选范围内
							// 移动选框时禁止滚动
							this.moveTime = true
							if (sto) {
								clearTimeout(sto)
							}
							sto = setTimeout(() => {
								this.moveTime = false
								clearTimeout(sto)
								sto = null
							}, 200)
							// 计算现在的点和原来的点的变化
							let x = this.touches[0].x - this.currentTouchPoint.x
							let y = this.touches[0].y - this.currentTouchPoint.y
							// 检测是否到边缘
							// if (x < 0) {
							//左移
							if (x < 0 && this.currentTouchPoint.x - this.fourPointRange[0].x1 >= this.currentTouchPoint
								.x) {
								x = 0
							}
							//右移
							if (x > 0 && this.fourPointRange[1].x2 - this.currentTouchPoint.x >= this.screenInfo.width -
								this.currentTouchPoint.x) {
								x = 0
							}
							// 上移
							if (y < 0 && this.currentTouchPoint.y - this.fourPointRange[0].y1 >= this.currentTouchPoint
								.y) {
								y = 0
							}
							// 下移
							if (y > 0 && this.fourPointRange[2].y2 - this.currentTouchPoint.y >= this.canvasHeight -
								this.currentTouchPoint.y) {
								y = 0
							}

							// 重新计算四点的位置
							this.fourPointRange.forEach(i => {
								i.x1 += x
								i.x2 += x
								i.y1 += y
								i.y2 += y
							})
							this.currentTouchPoint.x = this.touches[0].x
							this.currentTouchPoint.y = this.touches[0].y
							// 重绘四点
							this.drawFourPoint()

						}
					}
				}
				// 双指操作，进行缩放
				// if (this.touches.length == 2) {
				// 	// 计算两点之间的初始距离
				// 	let x = this.touches[0].x - this.touches[1].x
				// 	let y = this.touches[0].y - this.touches[1].y
				// 	if (this.oOffset == 0) {
				// 		this.oOffset = Math.sqrt(x * x + y * y)
				// 	} else {
				// 		// 计算扩大倍数
				// 		this.scaleCanvas = Math.sqrt(x * x + y * y) / this.oOffset

				// 	}
				// }
			},
			// 重新计算各点的位置
			reComPointPos(x, y, index) {
				// 0: 0 1 2
				// 1: 1 0 2 
				// 2: 2 0 3
				// 3: 3 1 2

				if (index == 0) {
					if (x >= this.fourPointRange[1].x1 - this.radius * 2) {
						x = this.fourPointRange[1].x1 - this.radius * 2
					}
					if (y >= this.fourPointRange[2].y1 - this.radius * 2) {
						y = this.fourPointRange[2].y1 - this.radius * 2
					}
				}
				if (index == 1) {
					if (x <= this.fourPointRange[0].x2 + this.radius * 2) {
						x = this.fourPointRange[0].x2 + this.radius * 2
					}
					if (y >= this.fourPointRange[2].y1 - this.radius * 2) {
						y = this.fourPointRange[2].y1 - this.radius * 2
					}
				}
				if (index == 2) {
					if (x >= this.fourPointRange[1].x1 - this.radius * 2) {
						x = this.fourPointRange[1].x1 - this.radius * 2
					}
					if (y <= this.fourPointRange[0].y2 + this.radius * 2) {
						y = this.fourPointRange[0].y2 + this.radius * 2
					}
				}
				if (index == 3) {
					if (x <= this.fourPointRange[0].x2 + this.radius * 2) {
						x = this.fourPointRange[0].x2 + this.radius * 2
					}
					if (y <= this.fourPointRange[0].y2 + this.radius * 2) {
						y = this.fourPointRange[0].y2 + this.radius * 2
					}
				}
				this.fourPointRange[index] = {
					x1: x - this.radius,
					y1: y - this.radius,
					x2: x + this.radius,
					y2: y + this.radius,
				}
				if (index == 0) {
					this.fourPointRange[1].y1 = this.fourPointRange[index].y1
					this.fourPointRange[1].y2 = this.fourPointRange[index].y2
					this.fourPointRange[2].x1 = this.fourPointRange[index].x1
					this.fourPointRange[2].x2 = this.fourPointRange[index].x2
				}
				if (index == 1) {
					this.fourPointRange[0].y1 = this.fourPointRange[index].y1
					this.fourPointRange[0].y2 = this.fourPointRange[index].y2
					this.fourPointRange[3].x1 = this.fourPointRange[index].x1
					this.fourPointRange[3].x2 = this.fourPointRange[index].x2
				}
				if (index == 2) {
					this.fourPointRange[3].y1 = this.fourPointRange[index].y1
					this.fourPointRange[3].y2 = this.fourPointRange[index].y2
					this.fourPointRange[0].x1 = this.fourPointRange[index].x1
					this.fourPointRange[0].x2 = this.fourPointRange[index].x2
				}
				if (index == 3) {
					this.fourPointRange[2].y1 = this.fourPointRange[index].y1
					this.fourPointRange[2].y2 = this.fourPointRange[index].y2
					this.fourPointRange[1].x1 = this.fourPointRange[index].x1
					this.fourPointRange[1].x2 = this.fourPointRange[index].x2
				}

			},
			// 重新绘制时间
			reDrawTime() {
				// 当前时间
				timeCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				timeCanvas.strokeText(this.dateTimeInfo.nowTime, this.dateTimeInfo.left, this.dateTimeInfo.top, 120)
				timeCanvas.fillText(this.dateTimeInfo.nowTime, this.dateTimeInfo.left, this.dateTimeInfo.top, 120)
				timeCanvas.draw(true) //默认false，false会将之前的清空
			},
			// 重新绘制地点
			reDrawAddress() {
				addressCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				addressCanvas.strokeText(this.addressInfo.currentAdd, this.addressInfo.left, this.addressInfo.top, this
					.addressInfo.addressWidth)
				addressCanvas.fillText(this.addressInfo.currentAdd, this.addressInfo.left, this.addressInfo.top, this
					.addressInfo.addressWidth)
				addressCanvas.draw(true) //默认false，false会将之前的清空
			},
			// 在canvas上加标记
			async addMark(index) {
				if (index == 'time') {
					if (!this.dateTimeInfo.hash) {
						timeCanvas.setFontSize(14)
						timeCanvas.setLineWidth(4)
						timeCanvas.setFillStyle('rgb(83, 83, 83)')
						timeCanvas.setStrokeStyle('white')
						// 当前时间
						let nowTime = getNowDateTime()
						this.dateTimeInfo.nowTime = nowTime
						this.dateTimeInfo.left = 5
						this.dateTimeInfo.top = this.canvasHeight - 10
						timeCanvas.strokeText(nowTime, this.dateTimeInfo.left, this.dateTimeInfo.top, 120)
						timeCanvas.fillText(nowTime, this.dateTimeInfo.left, this.dateTimeInfo.top, 120)
						this.dateTimeInfo.hash = true
						timeCanvas.draw(true) //默认false，false会将之前的清空
					} else {
						// 移除时间
						timeCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
						timeCanvas.draw(true) //默认false，false会将之前的清空
						this.dateTimeInfo.hash = false
					}
				}
				// 添加地点
				if (index == 'address') {
					if (!this.addressInfo.hash) {
						addressCanvas.setFontSize(14)
						addressCanvas.setLineWidth(4)
						addressCanvas.setFillStyle('rgb(83, 83, 83)')
						addressCanvas.setStrokeStyle('white')
						// 当前位置
						// var geolocation = new AMap.Geolocation({
						// 	enableHighAccuracy: true, //是否使用高精度定位，默认:true
						// 	timeout: 10000, //超过10秒后停止定位，默认：5s
						// 	buttonPosition: 'RB', //定位按钮的停靠位置
						// });
						// geolocation.getCurrentPosition(function(status, result) {
						// 	if (status == 'complete') {
						// 	} else {
						// 	}
						// });
						uni.getLocation({
							// type: 'gcj02',
							success: (res) => {
								uni.request({
									header: {
										"Content-Type": "application/text"
									},
									//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
									url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' +
										res.longitude + ',' +
										res.latitude + '&key=' + amapKey +
										'&radius=1000&extensions=all',
									success: (re) => {
										console.log(re);
										if (re.statusCode === 200 && re.data.status == 1) {
											let currentAdd = re.data.regeocode
												.formatted_address
											this.addressInfo.currentAdd = currentAdd
											let fc = currentAdd.length //字数
											let fs = 14
											this.addressInfo.addressWidth = fc * fs
											this.addressInfo.left = 5
											this.addressInfo.top = this.canvasHeight - 40
											addressCanvas.setFontSize(fs)
											addressCanvas.strokeText(currentAdd, this
												.addressInfo
												.left,
												this.addressInfo
												.top, this.addressInfo
												.addressWidth)
											addressCanvas.fillText(currentAdd, this.addressInfo
												.left,
												this
												.addressInfo.top,
												this.addressInfo
												.addressWidth)
											this.addressInfo.hash = true
											addressCanvas.draw(true) //默认false，false会将之前的清空
										} else {
											uni.showToast({
												icon: 'none',
												title: '获取信息失败，请确认是否开启定位'
											})
										}

									}
								});

							},
							fail: (err) => {
								uni.showToast({
									icon: 'none',
									title: '获取位置失败,详情查看控制台'
								})
								uni.showModal({
									content:JSON.stringify(err)+'，请查看插件注意事项！！！'
								})
								console.error("错误信息:");
								console.error(
									'1.请确认是否已经在uni_modules/jack-filepicker/common/config.js 中 配置 amapKey (高德服务key) ,且申请类型为Web服务类型'
									);
								console.error(
									'2.请在dege中调试(推荐);或者使用https协议的域名代理到本地址进行访问;也可以发布到服务器使用https域名访问');
							},
							complete(res) {
								console.log(res);
							}
						});

					} else {
						// 移除
						addressCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
						addressCanvas.draw(true) //默认false，false会将之前的清空
						this.addressInfo.hash = false
					}
				}
				// 旋转
				if (index == 'rotate') {
					// 三个绘制图层上是否有内容
					let timeCanvas = {
						canvasId: "timeCanvas",
						x: 0,
						y: 0,
						width: this.screenInfo.width,
						height: this.canvasHeight,
					}
					let drawCanvas = {
						canvasId: "drawCanvas",
						x: 0,
						y: 0,
						width: this.screenInfo.width,
						height: this.canvasHeight,
					}
					let addressCanvas = {
						canvasId: "addressCanvas",
						x: 0,
						y: 0,
						width: this.screenInfo.width,
						height: this.canvasHeight,
					}
					let c1 = await canvasHasContent(timeCanvas, this)
					let c2 = await canvasHasContent(drawCanvas, this)
					let c3 = await canvasHasContent(addressCanvas, this)
					if (c1 || c2 || c3) {
						uni.showModal({
							cancelText: '旋转',
							confirmText: '取消旋转',
							title: '旋转将清除图片上的编辑内容',
							content: '是否继续？',
							success: (res) => {
								if (res.cancel) {
									// 继续旋转
									this.rotateClearOther()
								}
							}
						})
					} else {
						this.rotateClearOther()
					}
				}
				// 绘制涂鸦
				if (index == 'draw') {
					this.canDraw = !this.canDraw
					this.isClip = false
				}
				// 保存修改
				if (index == 'save') {
					// #ifdef H5
					const canvasList = document.querySelectorAll("uni-canvas>canvas");
					const newCanvas = document.createElement('canvas')
					newCanvas.width = this.screenInfo.width
					newCanvas.height = this.canvasHeight
					const context = newCanvas.getContext('2d')
					
					// 保存图片后模糊的问题
					var devicePixelRatio = window.devicePixelRatio || 1,
						backingStoreRatio = context.webkitBackingStorePixelRatio ||
						context.mozBackingStorePixelRatio ||
						context.msBackingStorePixelRatio ||
						context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1,
						ratio = devicePixelRatio / backingStoreRatio;
					
					var oldWidth = newCanvas.width;
					var oldHeight = newCanvas.height;
					newCanvas.width = oldWidth * ratio;
					newCanvas.height = oldHeight * ratio;
					newCanvas.style.width = oldWidth + 'px';
					newCanvas.style.height = oldHeight + 'px';
					context.scale(ratio, ratio);
					
					canvasList.forEach(item => {
						if (item.getAttribute('width') == 0 || item.getAttribute('height') == 0);
						else {
							context.drawImage(item, 0, 0, this.screenInfo.width, this.canvasHeight)
						}
					})
					let base64 = newCanvas.toDataURL();
					// 将处理好的图片生成临时url
					let url = blobToUrl(base64toBlob(base64))
					this.selectedList.push(url)
					// 清空画布并关闭弹窗
					this.clearCanvas()
					this.$emit('finishEdit', url)
					// // 默认将处理好的blobUrl存到父组件v-model绑定中，若上传后需要将url绑定到v-model中手动清除原来
					// this.$emit('finishEdit', url)
					// #endif
					// #ifdef MP-WEIXIN
					this.itemCanvasInfo.width = this.screenInfo.width
					this.itemCanvasInfo.height = this.canvasHeight
					uni.showLoading({
						mask: true
					})
					// 将所有图层绘制到newCanvas中
					this.canvasListIds.forEach(async (i, index) => {
						let result = await wx.canvasToTempFilePath({
							canvasId: i,
						}, this)
						let url = result.tempFilePath
						newCanvas.drawImage(url, 0, 0, this.itemCanvasInfo.width, this
							.itemCanvasInfo
							.height)
						newCanvas.draw(true)
						if (index == this.canvasListIds.length - 1) {
							let result = await wx.canvasToTempFilePath({
								canvasId: 'newCanvas',
							}, this)
							let urlr = result.tempFilePath
							this.selectedList.push(urlr)
							// 清空画布并关闭弹窗
							this.clearCanvasContent()
							this.clearCanvas()
							this.$emit('finishEdit', urlr)
							uni.hideLoading()
						}
					})
					// #endif
				}
				// 裁剪
				if (index == 'clip') {
					this.isClip = !this.isClip
					// 绘制4个角的顶点
					if (this.isClip) {
						this.fourPointRange = []
						// 初始距离边缘的偏移
						let offset = 40
						this.fourPointRange.push({
							x1: 0 + offset,
							y1: 0 + offset,
							x2: this.radius * 2 + offset,
							y2: this.radius * 2 + offset
						})
						this.fourPointRange.push({
							x1: this.screenInfo.width - this.radius * 2 - offset,
							y1: 0 + offset,
							x2: this.screenInfo.width - offset,
							y2: this.radius * 2 + offset
						})
						this.fourPointRange.push({
							x1: 0 + offset,
							y1: this.canvasHeight - this.radius * 2 - offset,
							x2: this.radius * 2 + offset,
							y2: this.canvasHeight - offset
						})
						this.fourPointRange.push({
							x1: this.screenInfo.width - this.radius * 2 - offset,
							y1: this.canvasHeight - this.radius * 2 - offset,
							x2: this.screenInfo.width - offset,
							y2: this.canvasHeight - offset
						})

						this.drawFourPoint()

					}
				}

			},
			// 绘制4个顶点
			drawFourPoint() {
				clipCanvas.setFillStyle('rgba(0,0,0,0.6)')
				clipCanvas.fillRect(0, 0, this.screenInfo.width, this.canvasHeight)
				clipCanvas.clearRect(this.fourPointRange[0].x1, this.fourPointRange[0].y1, this.fourPointRange[1].x2 - this
					.fourPointRange[0].x1, this.fourPointRange[2].y2 - this.fourPointRange[0].y1)
				clipCanvas.setStrokeStyle('gray')
				clipCanvas.setFillStyle('white')
				this.fourPointRange.forEach((i, index) => {
					clipCanvas.beginPath()
					clipCanvas.arc(i.x1 + (i.x2 - i.x1) / 2, i.y1 + (i.y2 - i.y1) / 2, this.radius, 0, 360)
					clipCanvas.fill()
					clipCanvas.beginPath()
					clipCanvas.arc(i.x1 + (i.x2 - i.x1) / 2, i.y1 + (i.y2 - i.y1) / 2, this.radius, 0, 360)
					clipCanvas.stroke()
				})
				clipCanvas.draw()
				this.isClip = true
				this.canDraw = false
				let clipW = this.fourPointRange[1].x2 - this.fourPointRange[0].x1
				let clipH = this.fourPointRange[2].y2 - this.fourPointRange[0].y1
				this.itemCanvasInfo.width = clipW
				this.itemCanvasInfo.height = clipH
			},
			// 裁剪后重新绘制
			afterClipDraw(url) {
				uni.getImageInfo({
					src: url,
					success: (res) => {
						let imageW = res.width
						let imageH = res.height
						// 清除
						this.clearCanvasContent()
						this.canvasHeight = (imageH / imageW) * this.screenInfo.width
						this.currentImage = res.path
						uni.showLoading({
							mask: true
						})
						setTimeout(() => {
							uni.hideLoading()
							imgCanvas.drawImage(this.currentImage, 0, 0, this.screenInfo.width,
								this.canvasHeight)
							imgCanvas.draw()
							this.dateTimeInfo.hash = false
							this.itemCanvasInfo.width = 0
							this.itemCanvasInfo.height = 0
						}, 100)
					},
					fail: (err) => {
						console.log(err);
					}
				})

			},
			// 旋转图片，清除其他层上的内容
			async rotateClearOther() {
				uni.showLoading({
					mask: true
				})
				this.rotateDeg += 90
				// 清除
				this.clearCanvasContent()

				// 重新计算canvas宽高
				// 现在的高=(screenWidth/canvasH)*screenWidth,
				this.canvasHeight = (this.screenInfo.width / this.canvasHeight) * this.screenInfo.width
				setTimeout(async () => {
					let imgurl = await urlImgRotate(this.currentImage, this.rotateDeg, this)
					uni.getImageInfo({
						src: imgurl
					}).then(res => {
						console.log('===========返回图片宽高');
						console.log(res);
					})
					imgCanvas.drawImage(imgurl, 0, 0,
						this.screenInfo.width,
						this.canvasHeight)
					imgCanvas.draw(false, async () => {
						this.dateTimeInfo.hash = false
						this.addressInfo.hash = false
						uni.hideLoading()

						// let k = await uni.canvasToTempFilePath({
						// 	canvasId: 'imgCanvas',
						// 	quality: 1,
						// 	fileType: 'png'
						// }, this)
						// this.currentImage = k.tempFilePath
					})
				})
			},
			// 加载图片到canvas
			loadImgToCanvas() {
				let w = this.currentImgInfo.width
				let h = this.currentImgInfo.height
				// 计算比例
				let ro = w / h
				this.canvasHeight = this.screenInfo.width / ro
				setTimeout(() => {
					console.log(this.currentImage, this.screenInfo, ro, imgCanvas);
					imgCanvas.drawImage(this.currentImage, 0, 0, this.screenInfo.width, this.screenInfo
						.width / ro)
					imgCanvas.draw()
				}, 100)
			},
			async select(e) {
				console.log(this.$refs.filepicker.filesList);
			},
			chooseFile() {
				uni.chooseImage({
					count: 1,
					extension: this.fileExtname,
					sourceType: this.sourceType,
					complete: (e) => {
						// 获取已经选择的文件对象
						this.currentImage = e.tempFilePaths[0]
						uni.getImageInfo({
							src: e.tempFilePaths[0]
						}).then(res => {
							this.currentImgInfo = res
							this.$refs.popup.open()
							this.$nextTick(() => {
								this.loadImgToCanvas()
							})
						})
					}
				})
			},
			// 清空画布内容
			clearCanvasContent() {
				// #ifdef MP-WEIXIN
				newCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				newCanvas.draw()
				// #endif
				imgCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				timeCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				drawCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				clipCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				itemCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				addressCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
				imgCanvas.draw()
				timeCanvas.draw()
				drawCanvas.draw()
				clipCanvas.draw()
				itemCanvas.draw()
				addressCanvas.draw()
			},
			/**
			 * 清空画布并关闭弹窗
			 */
			clearCanvas() {
				this.canDraw = false
				this.dateTimeInfo.hash = false
				this.addressInfo.hash = false
				this.$refs.popup.close()
				this.rotateDeg = 0
			},
			// 每一张itemCanvas画布内容绘制到一个里newCanvas
			itemsToNewH5(context, newCanvas, index) {
				let itemCanvast = this.$refs.itemCanvas.$el
				let c = itemCanvast.children[0]
				this.currentImage = c
				uni.showLoading({
					mask: true
				})
				setTimeout(() => {
					uni.hideLoading()
					context.drawImage(c, 0, 0, newCanvas.width, newCanvas.height)
					if (index == 3) {
						let base64 = newCanvas.toDataURL();
						// 将处理好的图片生成临时url
						let url = blobToUrl(base64toBlob(base64))
						// 重新绘制图像到画布，重置其他所有画布
						this.afterClipDraw(url)

					}
				}, 100)
			},
			itemsToNewWX(index) {
				uni.canvasToTempFilePath({
					canvasId: 'itemCanvas',
					success: res => {
						newCanvas.drawImage(res.tempFilePath, 0, 0, this.itemCanvasInfo.width, this
							.itemCanvasInfo.height)
						newCanvas.draw(true)

						if (index == 3) {
							uni.canvasToTempFilePath({
								canvasId: 'newCanvas',
							}, this).then(res => {
								this.clearCanvasContent()
								// 重新绘制图像到画布，重置其他所有画布
								this.afterClipDraw(res.tempFilePath)
							})
						}

					},
					fail: err => {
						console.log(err);
					}
				}, this)
			},
			// 保留裁剪
			async saveClip() {
				// #ifdef H5
				const newCanvas = document.createElement('canvas')
				newCanvas.width = this.fourPointRange[1].x2 - this.fourPointRange[0].x1
				newCanvas.height = this.fourPointRange[2].y2 - this.fourPointRange[0].y1
				const context = newCanvas.getContext('2d')
				// #endif
				for (let index = 0; index < this.canvasListIds.length; index++) {
					// 去除裁剪图层
					let res = await uni.canvasGetImageData({
						canvasId: this.canvasListIds[index],
						x: this.fourPointRange[0].x1,
						y: this.fourPointRange[0].y1,
						width: this.itemCanvasInfo.width,
						height: this.itemCanvasInfo.height,

					}, this)
					// 将每一个画布的数据放入itemCanvas中
					// #ifdef MP-WEIXIN
					try {
						await uni.canvasPutImageData({
							canvasId: 'itemCanvas',
							data: res.data,
							x: 0,
							y: 0,
							width: Math.floor(this.itemCanvasInfo
								.width), //宽高取整，否则报  canvasputimagedata:fail invalid data format
							height: Math.floor(this.itemCanvasInfo.height),
						}, this)
					} catch (e) {
						console.log(e);
						console.log('若使用微信小程序端，请使用真机调试裁剪功能');
					}
					// #endif
					// #ifdef H5
					try {
						await uni.canvasPutImageData({
							canvasId: 'itemCanvas',
							data: res.data,
							x: 0,
							y: 0,
							width: this.itemCanvasInfo.width,
						}, this)
					} catch (e) {
						console.log(e);
					}
					// #endif
					// 将每一张itemCanvas画布内容绘制到一个newCanvas里
					// #ifdef H5
					this.itemsToNewH5(context, newCanvas, index)
					// #endif
					// #ifdef MP-WEIXIN
					this.itemsToNewWX(index)
					// #endif
				}
			},
			initMap() {
				window._AMapSecurityConfig = {
					securityJsCode: securityJsCode,
				};
				AMapLoader.load({
						key: amapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Geocoder", "AMap.Geolocation"], //需要使用的的插件列表，
					})
					.then((AMap) => {
						this.AMap = AMap
					})
					.catch((e) => {
						console.log(e);
					});
			}

		},
		mounted() {
			// #ifdef MP-WEIXIN
			newCanvas = uni.createCanvasContext('newCanvas', this)
			// #endif
			imgCanvas = uni.createCanvasContext('imgCanvas', this)
			timeCanvas = uni.createCanvasContext('timeCanvas', this)
			drawCanvas = uni.createCanvasContext('drawCanvas', this)
			clipCanvas = uni.createCanvasContext('clipCanvas', this)
			itemCanvas = uni.createCanvasContext('itemCanvas', this)
			addressCanvas = uni.createCanvasContext('addressCanvas', this)
			uni.getSystemInfo().then(res => {
				this.screenInfo.width = res.windowWidth
				this.screenInfo.height = res.windowHeight
			})
			this.canvasListIds = ['imgCanvas', 'drawCanvas', 'timeCanvas', 'addressCanvas']
		},
		computed: {
			notMoveCanvas() {
				return this.moveTime || this.canDraw || this.moveAddress
			},
			// 按钮可用状态
			btnCanotUse() {
				return this.isClip || this.canDraw
			},
		},
		watch: {
			isClip(n) {
				if (!n) {
					// 将itemCanvas宽高设置成裁剪宽高
					this.itemCanvasInfo.width = this.fourPointRange[1].x2 - this.fourPointRange[0].x1
					this.itemCanvasInfo.height = this.fourPointRange[2].y2 - this.fourPointRange[0].y1
					uni.showModal({
						cancelText: '舍弃',
						confirmText: '保留',
						title: '是否保留裁剪区域',
						success: (res) => {
							if (res.confirm) {
								this.saveClip()
							}
							if (res.cancel) {
								clipCanvas.clearRect(0, 0, this.screenInfo.width, this.canvasHeight)
								clipCanvas.draw()
								this.itemCanvasInfo.width = 0
								this.itemCanvasInfo.height = 0
							}
						}
					})
				}
			},
			value: {
				handler() {
					this.selectedList = JSON.parse(JSON.stringify(this.value))
				},
				immediate: true,
				deep: true
			}
		},
		created() {
			// #ifdef H5
			this.initMap()
			// #endif
		}
	}
</script>
<style>
	@import url('index.css');
</style>